import type { DeckDetail, CreateDeck } from '/@/api/currentDeck/model/deckModel';
import ClipboardJS from 'clipboard';
import { ReviewStatusEnum } from '/@/api/currentDeck/model/deckModel';
import { defineComponent, reactive, ref } from 'vue';
import { appShareParamsEncrypt, appShareUsing } from '/@/utils/appInteractive';
import { useGlobSetting } from '/@/hooks/setting';
import { useGo } from '/@/hooks/web/usePage';
import { useCurrentDeckStore } from '/@/store/modules/currentDeck';
import { useCurrentDeckConfigHooks } from '/@/views/currentDeck/hooks/useConfigs';
import { useMessage } from '/@/hooks/web/useMessage';
import { useExportHooks } from '/@/views/deskSet/hooks/useExport';
import { aTabClick, awaitWrap, getTokenUrl, textExtractUrl } from '/@/utils';
import { isArray } from '/@/utils/is';
import { formatToDateTime } from '/@/utils/dateUtil';
import Title from '/@/views/general/components/Title';
import { Skeleton, Button, Tag } from 'vant';
import { Icon } from '/@/components/Icon';
import DeckDescPopup from './components/DeckDescPopup';
import DeckTagPopup from './components/DeckTagPopup';
import DeckSelectedCardList from '/@/views/currentDeck/components/DeckSelectedCardList';
import { DeckDetailApi, ModifyDeckApi } from '/@/api/currentDeck/deck';
import { SetDeckCopyApi } from '/@/api/deckSet/setDeck';

import('./index.less');

export default defineComponent({
  name: 'CurrentDeckDetailPage',
  props: {
    deckId: {
      type: String as PropType<string>,
      required: true,
    },
    share: {
      type: String as PropType<string>,
      default: () => {
        return '';
      },
    },
    gameId: {
      type: String as PropType<string>,
      default: () => {
        return '';
      },
    },
  },
  setup(props) {
    const currentStore = useCurrentDeckStore();

    const shareUrl = `${useGlobSetting().gadgetsUrl}/templatedeck/index.html#/setdeckdetail/${props.deckId}/${
      currentStore.getGameId
    }?share=1`;

    const content = {
      title: '旅法师营地套牌',
      content: '我通过旅法师营地跟你分享了套牌，点击查看',
      image: 'https://pic.iyingdi.com/yingdi_mobile/yingdi-logo.png',
      url: shareUrl,
    };

    // 如果是分享页面则重新获取配置
    if (props.share) {
      currentStore.setGameId(props.gameId);
      const {} = useCurrentDeckConfigHooks({ game_id: props.gameId });
    }

    // 设置分享参数
    appShareUsing(content);

    // 导出组件
    const { UseExport } = useExportHooks();

    const go = useGo();
    const { createInfoToast, createSuccessToast, createFailToast } = useMessage();
    const deckDetailInfo = reactive<DeckDetail>({} as DeckDetail);
    const loadingState = ref(true);

    const getDetail = async () => {
      const [error, data] = await awaitWrap(DeckDetailApi({ deck_id: Number(props.deckId) }));
      if (error) {
        return false;
      }
      const result = data as DeckDetail;
      for (const item in result) {
        deckDetailInfo[item] = result[item];
      }
      deckDetailInfo.tags = isArray(result.tags) ? result.tags : [];
      loadingState.value = false;
      currentStore.setDeckId(result.deck_id);
      currentStore.setDeckInfo(result.deck_info);
    };
    getDetail();

    // 卡牌标题
    const DeckBasicInfoArea = () => {
      let spanAbbr: VueNode = null;
      switch (deckDetailInfo.review_status) {
        case ReviewStatusEnum.ING:
          spanAbbr = <span class={'text-red-500'}>（审核中）</span>;
          break;
        case ReviewStatusEnum.FAIL:
          spanAbbr = <span class={'text-red-500'}>（未通过）</span>;
          break;
      }
      return (
        <ul class={'deck-basic-info-area'}>
          <li class={'flex justify-between'}>
            <div class={'flex-1'}>
              <span class={'font-bold'}>套牌名称：</span>
              {deckDetailInfo.deck_name}
            </div>
            {spanAbbr}
          </li>
          <li class={'flex justify-between'}>
            <div class={'flex-1'}>
              <span class={'font-bold'}>
                套牌ID<span class={'mx-[14px]'}></span>：
              </span>
              {deckDetailInfo.deck_id}
              <span onClick={copyDeckId}>
                <Icon class={'!text-sm ml-sm text-blue-500 copy-deck-id'} icon={'ic:round-content-copy'} />
              </span>
            </div>
          </li>
          {currentStore.getDeckConfig.has_price ? (
            <li>
              <span class={'font-bold'}>预估售价：</span>
              {deckDetailInfo.price ? <>{deckDetailInfo.price / 100}元</> : <span>暂无</span>}
            </li>
          ) : null}
          <li>
            <span class={'font-bold'}>更新时间：</span>
            {formatToDateTime(deckDetailInfo.updated_at, 'YYYY-MM-DD')}
          </li>
          <li class={'bg-gray-100 px-10px pb-5px min-h-50px'}>
            <div>
              <Button
                icon={'edit'}
                class={'!text-blue-500 !border-0 !bg-gray-100'}
                size={'mini'}
                onClick={() => {
                  descPopupState.value = true;
                }}
              >
                描述
              </Button>
            </div>
            <p
              class={'text-xs text-gray-500 whitespace-pre-line break-all'}
              v-html={textExtractUrl(deckDetailInfo.deck_desc)}
            ></p>
          </li>
          {currentStore.getDeckConfig.tags.length ? (
            <li class={'flex flex-wrap items-center mt-sm'}>
              <Button
                icon={'plus'}
                class={'!text-blue-500 !border-0 !mr-md'}
                size={'mini'}
                onClick={() => {
                  tagPopupState.value = true;
                }}
              >
                添加标签
              </Button>
              {deckDetailInfo.tags.map((text) => {
                return (
                  <Tag color={'linear-gradient(142deg, #4396ff 0%, #086acc 100%)'} class='mr-sm'>
                    {text}
                  </Tag>
                );
              })}
            </li>
          ) : null}
        </ul>
      );
    };

    // 复制套牌ID
    const copyDeckId = () => {
      const clipboard = new ClipboardJS('.copy-deck-id', {
        text: function () {
          return String(deckDetailInfo.deck_id);
        },
      });
      clipboard.on('success', function () {
        createSuccessToast({
          message: '套牌ID已复制',
        });
      });
      clipboard.on('error', function () {
        createFailToast({
          message: '复制套牌ID失败',
        });
      });
    };

    // 修改描述
    const modifyDescEmit = async (deckDesc: string) => {
      deckDetailInfo.deck_desc = deckDesc;
      const params: CreateDeck = {
        deck_id: props.deckId,
        deck_name: deckDetailInfo.deck_name,
        deck_desc: deckDesc,
        deck_info: deckDetailInfo.deck_info,
        is_open: deckDetailInfo.is_open || 0,
        tags: deckDetailInfo.tags || [],
      } as unknown as CreateDeck;
      const [error] = await awaitWrap(ModifyDeckApi(params));
      if (error) {
        return;
      }
      createInfoToast({ message: '套牌描述已修改，审核通过后展示' });
    };
    // 复制套牌
    const copyDeck = async () => {
      const [error] = await awaitWrap(SetDeckCopyApi({ deck_id: deckDetailInfo.deck_id }));
      if (error) {
        return;
      }
      createInfoToast({
        overlay: true,
        message: '复制成功, 请到我的套牌查看',
      });
    };
    // 修改公开状态
    const modifyIsOpenClick = async () => {
      const openState = deckDetailInfo.is_open ? 0 : 1;
      const params: CreateDeck = {
        deck_id: props.deckId,
        deck_name: deckDetailInfo.deck_name,
        deck_desc: deckDetailInfo.deck_desc,
        deck_info: deckDetailInfo.deck_info,
        is_open: openState,
        tags: deckDetailInfo.tags || [],
      } as unknown as CreateDeck;
      const [error] = await awaitWrap(ModifyDeckApi(params));
      if (error) {
        return;
      }
      deckDetailInfo.is_open = openState;
    };
    // 修改标签
    const modifyTagsEmit = async (tags: string[]) => {
      const params: CreateDeck = {
        deck_id: props.deckId,
        deck_name: deckDetailInfo.deck_name,
        deck_desc: deckDetailInfo.deck_desc,
        deck_info: deckDetailInfo.deck_info,
        is_open: deckDetailInfo.is_open,
        tags: tags,
      } as unknown as CreateDeck;
      const [error] = await awaitWrap(ModifyDeckApi(params));
      if (error) {
        return;
      }
      deckDetailInfo.tags = tags;
    };
    // 分享事件
    const shareClick = () => {
      content.title = deckDetailInfo.deck_name;
      content.url = shareUrl;
      const base64str = appShareParamsEncrypt(JSON.stringify(content));
      aTabClick(`wanxiu://innerlink?type=webshareurl&parameters=${base64str}`);
    };

    // 浮层
    const descPopupState = ref(false);
    const tagPopupState = ref(false);

    return () => (
      <div class={'current-deck-detail-page'}>
        <Title
          title={deckDetailInfo.deck_name}
          leftArrow={!props.share}
          onLeftClick={() => {
            currentStore.clearCreateDeckParams();
            go(getTokenUrl(`/currentdeck/${currentStore.gameId}`), true);
          }}
        />
        <Skeleton title row={5} avatar loading={loadingState.value}>
          <div class={'detail-container'}>
            <DeckBasicInfoArea />
            <DeckSelectedCardList deckCardList={deckDetailInfo.deck_info} />
          </div>
        </Skeleton>

        {!props.share ? (
          <ul class={'action-area flex items-center justify-between'}>
            <li class={'exprot flex flex-col items-center'}>
              <UseExport gameId={currentStore.gameId} deckId={props.deckId} />
            </li>
            <li class={'share flex flex-col items-center'} onClick={copyDeck}>
              <Icon class={'!text-xl mb-sm'} icon={'ic:round-content-copy'} />
              <span>复制</span>
            </li>
            <li
              class={'modify flex flex-col items-center'}
              onClick={() => {
                go(`/currentdeckcreate/${props.deckId}`, true);
              }}
            >
              <Icon class={'!text-xl mb-sm'} icon={'material-symbols:edit-calendar-outline'} />
              <span>编辑</span>
            </li>
            <li class={'open flex flex-col items-center'} onClick={modifyIsOpenClick}>
              <Icon
                icon={deckDetailInfo.is_open ? 'mdi:eye-outline' : 'mdi:eye-off-outline'}
                class={'!text-xl mb-sm'}
              />
              <span>{deckDetailInfo.is_open ? '公开中' : '未公开'}</span>
            </li>
            <li class={'share flex flex-col items-center'} onClick={shareClick}>
              <Icon class={'!text-xl mb-sm'} icon={'ri:share-circle-line'} />
              <span>分享</span>
            </li>
          </ul>
        ) : null}

        <DeckDescPopup
          v-model:show={[descPopupState.value]}
          desc={deckDetailInfo.deck_desc || ''}
          onModifyDeckDesc={(deckDesc: string) => {
            modifyDescEmit(deckDesc);
          }}
        />
        <DeckTagPopup
          v-model:show={[tagPopupState.value]}
          tags={deckDetailInfo.tags || []}
          onModifyDeckTags={(tags: string[]) => {
            modifyTagsEmit(tags);
          }}
        />
      </div>
    );
  },
});
